//
//  LPActivityDetailPublishTellViewController.m
//  LovingPartyBuilding
//
//  Created by 刘应平 on 2017/6/9.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "LPActivityDetailPublishTellViewController.h"
#import "CBTextView.h"
#import "STPhotoBroswer.h"
#import "AlertWindow.h"
#import "LPShowImagesView.h"
#import "LPGainPath.h"
#import "JCAlertView.h"
#import "LCustomAlertView.h"
#import "ZLPhotoActionSheet.h"
@interface LPActivityDetailPublishTellViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,LPShowImagesViewDelegate,LCustomAlertDelegate,UITextViewDelegate>
{
    LCustomAlertView *_deleView;
    NSInteger _deleImageIndex;/**< 删除图片的下标 */
}
/**  textView  */
@property (strong, nonatomic)  CBTextView *tellTextView;
/**  图片显示视图  */
@property (strong, nonatomic) LPShowImagesView  *showImageView;
/**    */
@property (strong, nonatomic) JCAlertView  *jcAlertView;
/** 弹窗视图 */
@property (nonatomic, strong) JCAlertView *deleAlerView;

/**  分割线  */
@property (strong, nonatomic) UIView  *centerVIew;

/**  图片数组  */
@property (strong, nonatomic) NSMutableArray  *imagesArray;
/**  图片信息  */
@property (strong, nonatomic) NSMutableArray  *imagesInforArray;

/**  iamgepic  */
@property (strong, nonatomic) UIImagePickerController  *imagePickerController;
@end

@implementation LPActivityDetailPublishTellViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self peizhiNav];
    [self layoutUI];
    
}

#pragma mark - 界面
- (void)layoutUI{
    [self.view addSubview:self.tellTextView];
    self.centerVIew = [[UIView alloc] initWithFrame:CGRectMake(0, self.tellTextView.bottom, self.view.width, 1.5)];
    self.centerVIew.backgroundColor = [UIColor themeGrayColor];
    [self.view addSubview:self.centerVIew];
    
    [self addImage:self.imagesInforArray];
    
}


#pragma mark - 私有方法
- (void)peizhiNav{
    self.titlelabel.text = @"发表活动圈";
    [self.leftButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self.leftButton setTitle:@"取消" forState:UIControlStateNormal];
    self.rightButton.hidden = NO;
    [self.rightButton setTitle:@"发表" forState:UIControlStateNormal];

}

- (void)addImage:(NSArray *)images{
    if (self.showImageView) {
        [self.showImageView removeFromSuperview];
    }
     CGFloat heigth = ([UIScreen zj_screenWith] - 60 * [UIScreen zj_screenWScale]) / 4;
    NSInteger zheng = (images.count + 1) / 4;
    NSInteger yu = (images.count + 1) % 4;
    if (yu > 0) {
        zheng += 1;
    }
    self.showImageView = [[LPShowImagesView alloc] initWithFrame:CGRectMake(15 * [UIScreen zj_screenWScale], self.centerVIew.bottom + 20 * [UIScreen zj_screenHScale], [UIScreen zj_screenWith] - 30 * [UIScreen zj_screenWScale], heigth * zheng + 10 * [UIScreen zj_screenHScale] * (zheng - 1)) images:images];
    self.showImageView.delegate = self;
    [self.view addSubview:self.showImageView];
}




#pragma mark - LPShowImagesViewDelegate
- (void)lpShowImageWithView:(LPShowImagesView *)view clickImageVIewindex:(NSInteger)index{
    
    if (self.imagesInforArray.count > 8) {
        /**  这是放大图片  */
        STPhotoBroswer *broswer = [[STPhotoBroswer alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) ImageArray:self.imagesArray currentIndex:index];
        [broswer show];

    }else{
        if (index == self.imagesInforArray.count) {
            //图片多选模块
            ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
            //设置最大选择数量
            actionSheet.maxSelectCount = 9;
            //设置预览图最大数目
            actionSheet.maxPreviewCount = 16;
            __weak typeof(self) weakSelf = self;
            [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:nil completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
                
                [selectPhotos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    /** 这里是最多显示九张图片  */
                    if (self.imagesInforArray.count < 9) {
                        NSData * data = [ToolClass compressionImageWithImage:obj compressionMaxLimit:COMPRESSIONMAXLIMIT];
                        NetWorkUploadFileModel *model = [NetWorkUploadFileModel new];
                        model.FILE_NAME = [NSString stringWithFormat:@"%@.jpg",[NSDate getCurrentDate]];
                        model.FILE_INDEX = [NSString stringWithFormat:@"%ld",(unsigned long)idx];
                        model.FILE_PATH = data;
                        model.NAME = @"IMG_URL";
                        [weakSelf.imagesInforArray addObject:model];
                        NSDictionary *imageDic = @{@"image": obj};
                        [self.imagesArray addObject:imageDic];
                    }
                    
                    
                }];
                
                
                [self addImage:self.imagesArray];
            }];
        }else{
            /**  这是放大图片  */
            STPhotoBroswer *broswer = [[STPhotoBroswer alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) ImageArray:self.imagesArray currentIndex:index];
            [broswer show];
            
        }
    }
   
}

- (void)lpShowImageWithView:(LPShowImagesView *)view clickButtonindex:(NSInteger)index{
    _deleImageIndex = index;
    [self.deleAlerView show];
}



#pragma mark - 监听事件
- (void)action_rightButton:(UIButton *)sender{
    if (self.tellTextView.textView.text.length == 0 && self.imagesInforArray.count == 0 ) {
        [YJProgressHUD showMsgWithoutView:@"请添加图片或填写说说内容"];
        return;
    }
    __weak typeof(self) weakSelf = self;
    NetWorkUpLoadModel *loadModel = [NetWorkUpLoadModel new];
    loadModel.UPLOAD_FILES = self.imagesInforArray;
    loadModel.ACCOUNTID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID;
    loadModel.ACT_ID = self.model.ID;
    loadModel.CONTENT = self.tellTextView.textView.text;
    [YJProgressHUD showMessage:@"发表中..." duration:10 view:self.view];
    [NetWorkingManager uploadingWithXMLString:[NetWorkingURL getactmactionPublishChat] Parameter:loadModel Success:^(id object) {
        if ([object[@"STATE"] isEqualToString:@"20000"]) {
            [YJProgressHUD showSuccess:@"发表成功" inview:weakSelf.view];
            if (self.block) {
                self.block();
            }

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            [YJProgressHUD showSuccess:@"发表失败" inview:weakSelf.view];
        }
    } Fail:^(id object) {
        [YJProgressHUD showSuccess:@"网络错误" inview:weakSelf.view];
    }];
    
}


- (void)action_leftButton:(UIButton *)sender{
    if (self.tellTextView.textView.text.length != 0 || self.imagesInforArray.count != 0) {
        LCustomAlertView *alert = [[LCustomAlertView alloc] initWithFrame:self.view.bounds alertMessage:@"未发表说说，是否要退出" titlesArray:@[@"取消",@"确认"]];
        alert.delegate = self;
        self.jcAlertView = [[JCAlertView alloc]initWithCustomView:alert dismissWhenTouchedBackground:YES];
        [self.jcAlertView show];

    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark - LCustomAlertDelegate
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    if (view == _deleView) {
        [self.deleAlerView dismissWithCompletion:nil];
        if (index == 1) {
            [self.imagesInforArray removeObjectAtIndex:_deleImageIndex];
            [self.imagesArray removeObjectAtIndex:_deleImageIndex];
            [self addImage:self.imagesArray];
        }
    }else{
    if (index == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    [self.jcAlertView dismissWithCompletion:nil];
    }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        
        return NO;
        
    }
    
    NSString * toBeString = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if (toBeString.length >= 200) {
        textView.text = [toBeString substringToIndex:200];
        return NO;
    }
    
    
    return YES;
    
}

#pragma mark - getter
- (CBTextView *)tellTextView{
    if (_tellTextView == nil) {
        _tellTextView = [[CBTextView alloc] initWithFrame:CGRectMake(0, LP_TopHeight + 20 * [UIScreen zj_screenHScale], self.view.width, 130 * [UIScreen zj_screenHScale]) leftAndRigSpace:15 * [UIScreen zj_screenWScale] ];
        _tellTextView.placeHolder = @"在活动圈说点什么吧....";
        _tellTextView.placeHolderColor = [UIColor lightGrayColor];
        _tellTextView.textView.returnKeyType = UIKeyboardTypeTwitter;
        _tellTextView.aDelegate = self;
    }
    return _tellTextView;
}



- (NSMutableArray *)imagesInforArray{
    if (!_imagesInforArray) {
        _imagesInforArray = [NSMutableArray array];
    }
    return _imagesInforArray;
}

- (NSMutableArray *)imagesArray{
    if (!_imagesArray) {
        _imagesArray = [NSMutableArray array];
    }
    return _imagesArray;
}
- (JCAlertView *)deleAlerView{
    if (_deleAlerView == nil){
        _deleView = [[LCustomAlertView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], [UIScreen zj_screenHeight]) alertMessage:@"是否删除图片" titlesArray:@[@"取消",@"确认"]];
        _deleView.delegate = self;
        _deleAlerView = [[JCAlertView alloc] initWithCustomView:_deleView dismissWhenTouchedBackground:YES];
    }
    return _deleAlerView;
}
@end
